package com.hsd.whb.controller;

import com.hsd.whb.code.ValidateCodeProcessorHolder;
import com.hsd.whb.entity.Manager;
import com.hsd.whb.entity.Recorder;
import com.hsd.whb.enums.ResultEnum;
import com.hsd.whb.exception.HwbException;
import com.hsd.whb.pojo.input.ForgetPassword;
import com.hsd.whb.pojo.input.RegisterManager;
import com.hsd.whb.properties.SecurityConstants;
import com.hsd.whb.repository.ManagerRepository;
import com.hsd.whb.repository.RecorderRepository;
import com.hsd.whb.service.MailSenderService;
import com.hsd.whb.service.ManagerService;
import com.hsd.whb.service.RecorderService;
import com.hsd.whb.utils.BeanUtil;
import com.hsd.whb.utils.ResultVOUtil;
import com.hsd.whb.utils.ValidatorUtil;
import com.hsd.whb.pojo.output.ResultVO;
import com.wangjiacai.utils.utils.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;


@Controller
@RequestMapping("/loginAndRegister")
public class
LoginAndRegisterController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private ManagerRepository managerRepository;

    @Autowired
    private RecorderService recorderService;

    @Autowired
    private RecorderRepository recorderRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MailSenderService mailSenderService;

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    /*
     *登录页面
     */
    @GetMapping("/login")
    public String index(HttpServletRequest request) {
        request.setAttribute("loginProcessRecorderUrl", SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_RECORDER);
        request.setAttribute("loginProcessManagerUrl", SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MANAGER);
        request.setAttribute("registerUrl", SecurityConstants.DEFAULT_REGISTER_URL);
        return "login";
    }

    /*
     *注册页面
     */
    @GetMapping("/register")
    public String registerGet(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("registerUrl", SecurityConstants.DEFAULT_REGISTER_URL);
        return "register";
    }

    /*
     *注册
     */
    @PostMapping("/register")
    @ResponseBody
    public ResultVO registerPost(@Valid RegisterManager registerManager, BindingResult bindingResult) {
        ValidatorUtil.valid(bindingResult);
        Manager manager = new Manager();
        BeanUtil.copyProperties(registerManager, manager);
        managerService.register(manager);
        return ResultVOUtil.success("注册成功,请登录.");
    }

    @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}")
    public void createCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type)
            throws Exception {
        validateCodeProcessorHolder.findValidateCodeProcessor(type).create(new ServletWebRequest(request, response));
    }

    @PostMapping("/forgetPassword")
    @ResponseBody
    public ResultVO forgetPassword(@Valid ForgetPassword forgetPassword, BindingResult bindingResult) {
        ValidatorUtil.valid(bindingResult);
        String password = RandomStringUtils.randomNumeric(8);
        if (forgetPassword.getRole() == 1) {
            Manager manager = managerRepository.findByEmail(forgetPassword.getEmail());
            if (manager == null) throw new HwbException(ResultEnum.EMAIL_NOT_EXIST);
            manager.setPassword(passwordEncoder.encode(password));
            managerService.update(manager);
        } else {
            Recorder recorder = recorderRepository.findByEmail(forgetPassword.getEmail());
            if (recorder == null) throw new HwbException(ResultEnum.EMAIL_NOT_EXIST);
            recorder.setPassword(passwordEncoder.encode(password));
            recorderService.updateRecorder(recorder);
        }
        mailSenderService.sendMail(forgetPassword.getEmail(), "新密码", "这是你的新密码" + password + "，请登陆后及时修改密码");
        return ResultVOUtil.success("密码已经修改，请邮件查收");
    }
}
